package com.lg.my.netty.chart;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 实现简单的 逻辑
 *
 * @author by Mr. Li 2021/4/22 0:15
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
    //GlobalEventExecutor.INSTANCE 是全局的事件执行器，是一个单例
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 一旦有新的 channel 准备就绪 回调
     *
     * @param ctx ChannelHandlerContext
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 提醒上线
        // 获取上线的channel 信息
        final Channel channel = ctx.channel();
        // 这里只会通知已经上线的 channel
        channelGroup.writeAndFlush("[砰砰砰....您有好友上线了！！！ip：]" + channel.remoteAddress() + ",上线时间为：" + sdf.format(new Date()) + "\n");

        // 将上线的channel加入到 总的channel组中
        channelGroup.add(channel);
        System.out.println(channel.remoteAddress() + "上线了...." + "\n");
    }

    /**
     * channel 处于不活动状态 提示离线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[砰砰砰....您有好友下线了！！！ip：]" + channel.remoteAddress() + ",时间为：" + sdf.format(new Date()) + "\n");

        // 将上线的channel加入到 总的channel组中
        channelGroup.remove(channel);
        System.out.println(channel.remoteAddress() + "下线了...." + "\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "出现异常了。。。" + "\n");
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        // 使用自己的channel 通道进行通讯
        final Channel channel = channelHandlerContext.channel();

        assert channelGroup.size() != 0;
        channelGroup.forEach(channel1 -> {
            if (channel != channel1) {
                channel1.writeAndFlush("[客户端]" + channel1.remoteAddress() + " 发送消息：" + s + "\n");
            } else {
                channel.writeAndFlush("[自己给自己发送了一条消息：]" + s + "\n");
            }
        });

    }
}
